import { getLoginQrcode, logOut, getLoginStatus } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
const getDefaultState = () => {
  return {
    token: getToken(),
    qrCodeUrl: "", //小程序码
    userInfo: JSON.parse(localStorage.getItem("userInfo"))
  };
};

const qrcodeHttp = "http://mh.api.ushiningtech.com/api"; //小程序码的前缀域名地址

const state = getDefaultState();

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
  },
  SET_QRCODE: (state, qrCodeUrl) => {
    state.qrCodeUrl = qrcodeHttp + qrCodeUrl;
  }
};

const actions = {
  // getLoginQrcode //获取登录小程序码
  getLoginQrcode({ commit }) {
    return new Promise((resolve, reject) => {
      getLoginQrcode()
        .then(response => {
          const { data } = response;
          commit("SET_TOKEN", data.token);
          commit("SET_QRCODE", data.qrCodeUrl);
          setToken(data.token);
          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  // 获取登录状态
  getLoginStatus({ commit, state }) {
    return new Promise((resolve, reject) => {
      getLoginStatus({ token: state.token })
        .then(response => {
          const { data } = response;
          if (!data) {
            return reject("认证失败,请重新登录");
          }
          if (data.member && data.member.expire === 0) {
            data.dkUser ? (data.dkUser.memberFlag = true) : "";
          } else {
            data.dkUser ? (data.dkUser.memberFlag = false) : "";
          }
          commit("SET_USERINFO", data.dkUser);
          localStorage.setItem("userInfo", JSON.stringify(data.dkUser || null)); //存入本地存储
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  // user logout
  logOut({ commit, state }) {
    return new Promise((resolve, reject) => {
      logOut(state.token)
        .then(() => {
          removeToken(); // must remove  token  first ---全局钩子函数立即就会判断--立即进入登录页--不会进行拉去用户信息这些额外没必须的请求
          localStorage.removeItem("userInfo"); //移出用户信息
          resetRouter(); // 清空动态添加的路由 还原成默认的constantRoutes
          commit("RESET_STATE");
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken(); // must remove  token  first
      localStorage.removeItem("userInfo"); //移出用户信息
      commit("RESET_STATE");
      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
